package com.apes.enquiry.supplier.baturu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Date;
import java.util.Map;
import java.util.Scanner;

@Service
public class BaturuService {

    @Value("${baturu.url}")
    private String HOST;

    @Autowired
    private BaturuApi baturuApi;


    /**
     * 巴图鲁Get请求方式
     * @param urlNameString URL地址
     * @param param 请求参数
     * @return
     */
    public JSONObject doGet(String urlNameString, JSONObject param){
        JSONObject result = new JSONObject();
        try {
            URL realUrl = new URL(urlNameString);
            HttpsURLConnection httpConn = (HttpsURLConnection) realUrl.openConnection();
            httpConn.setRequestMethod("GET");

            httpConn.setRequestProperty("accessToken", baturuApi.getToken());
            httpConn.setRequestProperty("timestamp", String.valueOf(new Date().getTime()));
            httpConn.setRequestProperty("Content-Type", "application/json");

            httpConn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
            writer.write(param.toJSONString());
            writer.flush();
            writer.close();
            httpConn.getOutputStream().close();

            InputStream responseStream = httpConn.getResponseCode() / 100 == 2
                    ? httpConn.getInputStream()
                    : httpConn.getErrorStream();
            Scanner s = new Scanner(responseStream).useDelimiter("\\A");
            String response = s.hasNext() ? s.next() : "";
            result = JSONObject.parseObject(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 获取报价结果
     * @param request
     */
    public JSONObject queryQuote(SimpleRequest request){
        JSONObject map = (JSONObject) JSON.toJSON(MapUtil.mapper("userKey", "ff0c00cefbc749c", "inquiryNo", "ff0c00cefbc749c", "invoiceType", "2"));
        return baturuApi.queryQuote(map);
    }

    /**
     * 编码带出配件主名
     * @param body
     * @return
     */
    public JSONObject queryPartsName(JSONObject body){
        String method = "/open/parts/queryPartsName";
        return doGet(HOST + method, body);
    }

    /**
     * 编码带出epc图片
     * @param body
     * @return
     */
    public JSONObject queryOEImage(JSONObject body){
        String method = "/open/parts/queryOEImage";
        return doGet(HOST + method, body);
    }

}
